//
//  LAWriteReviewViewController.m
//  LYLazizDevelopDemo
//
//  Created by xbn_iMac on 2016/11/3.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LAWriteReviewViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "UIView+Rotation.h"
#import "LAWriteReviewScoreTableViewCell.h"
#import "LAWriteReviewTextTableViewCell.h"
#import "LAWriteReviewPictureTableViewCell.h"
#import "LAWriteReviewModel.h"
#import "LAWriteReviewTextTableViewCell.h"
#import "LZRestaurantHeaderViewControl.h"
#import "LZImagePickerManager.h"
#import "LZActionSheet.h"
#import "LZAlertView.h"
#import "LZUploadImagePresenter.h"
#import "LZUserOperationPresenter.h"
#import "LZRemindView.h"

typedef NS_ENUM(NSInteger ,UploadReviewStauts) {
    UploadReviewStauts_Default,                // 默认状态 ,没有请求的状态
    UploadReviewStauts_StartRequest,           // 开始请求的状态
    UploadReviewStauts_SuccessRequest,         // 请求成功的状态
    UploadReviewStauts_FaildRequest            // 请求失败的状态
};

@interface LAWriteReviewViewController ()<UITableViewDelegate,UITableViewDataSource,LZPictureManagerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (strong, nonatomic) LAWriteReviewModel *model;
@property (weak, nonatomic) LZActionSheet * sheetView;
@property (strong, nonatomic) LZImagePickerManager *pictureManager;
@property (strong, nonatomic) UIButton *rightButton;
@property (strong, nonatomic) LZRestaurantHeaderViewControl *restaurantHeaderView;

// ****************************** 餐厅评价的全局cell ******************************
@property (strong, nonatomic) LAWriteReviewTextTableViewCell *restaurant_reviewTextCell;
@property (strong, nonatomic) LAWriteReviewPictureTableViewCell *restaurant_reviewPictureCell;

// ****************************** 视频评价的全局cell ******************************
@property (strong, nonatomic) LAWriteReviewScoreTableViewCell *video_RatingScoreCell;
@property (strong, nonatomic) LAWriteReviewTextTableViewCell *video_reviewTextCell;
@property (strong, nonatomic) LAWriteReviewPictureTableViewCell *video_reviewPictureCell;


@property (strong, nonatomic) LAWriteReviewPictureTableViewCell *selected_reviewPictureCell;    // 用于记录是video里的还是餐馆里的选择图片

@property (assign, nonatomic) UploadReviewStauts restaurant_status; // 餐厅评价的上传状态
@property (assign, nonatomic) UploadReviewStauts video_status;      // 视频评价的上传状态

@end

@implementation LAWriteReviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"评论页面";
    
    self.title = LZLocalizedString(@"review_write", nil);
    [self configNavigationBarButton];
    self.table.separatorColor = [UIColor clearColor];
    [self configData];
    
    [self regisiterAndCreateCell];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    
}

#pragma
#pragma mark - private method
#pragma mark - request 

- (void)requestUplodModel {
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    // 上传评论数据需先上传图片，且需要一个一个的上传图片
    self.rightButton.userInteractionEnabled = NO;
    if (self.type == WriteReviewType_Video) {
        // 上传视频的评价
        if (self.video_status != UploadReviewStauts_SuccessRequest) {
            [self requestUploadVideoImage];
        }
       
        if (self.restaurant_status != UploadReviewStauts_SuccessRequest) {
            if (self.model.restaurant_taste>0) {
                // 如果有餐厅类的评价则上传餐厅的评价
                [self requestUploadRestaurantImage];
            }
        }
    }
    else if (self.type == WriteReviewType_Restaurant){
        // 上传餐厅的评价
        if (self.restaurant_status != UploadReviewStauts_SuccessRequest) {
            [self requestUploadRestaurantImage];
        }
    }
}

// ****************************** 餐厅 ******************************
// 添加餐厅的评论
- (void)requestUploadRestaurantImage {
    self.restaurant_status = UploadReviewStauts_StartRequest;
    if (self.restaurant_reviewPictureCell.arrImages.count>0) {
        NSMutableArray *taskArray = [NSMutableArray array];
        WS(weakSelf)
        for (int i = 0; i<self.restaurant_reviewPictureCell.arrImages.count; i++) {
            NSURLSessionDataTask *task = [self requestUploadImage:self.restaurant_reviewPictureCell.arrImages[i] andBusinessId:nil andBusinessType:@"7" andBusinessNo:[NSString stringWithFormat:@"%d",i] andCount:1 andSuccessBlock:^(id data) {
                [weakSelf addRestaurantImageUrl:data];
            } andFaildBlcok:^{
                DLog(@"餐厅类上传图片失败了！！！");
                for (NSURLSessionDataTask *tempTask in taskArray) {
                    [tempTask cancel];
                }
                [taskArray removeAllObjects];
                [weakSelf.model.video_images removeAllObjects];
                weakSelf.restaurant_status = UploadReviewStauts_FaildRequest;
                [weakSelf checkUploadRequestStatus];
            }];
            [taskArray addObject:task];
        }
    }
    else {
        [self requestUploadRestaurantModel];
    }
}

// 存餐厅类上传的图片的url
- (void)addRestaurantImageUrl:(NSString*)url {
    [self.model.restaurant_images addObject:url];
    if (self.model.restaurant_images.count == self.restaurant_reviewPictureCell.arrImages.count) {
        [self requestUploadRestaurantModel];
    }
}

// 上传餐厅的评价
- (void)requestUploadRestaurantModel {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.sellerId forKey:@"sellerId"];              // 商户id
    [parameters setObject:[NSNumber numberWithInteger:self.model.restaurant_rating] forKey:@"commentScore"];          // 评论分数
    [parameters setObject:[NSNumber numberWithInteger:self.model.restaurant_taste] forKey:@"commentTaste"];          // 口味分数
    [parameters setObject:[NSNumber numberWithInteger:self.model.restaurant_atmopsphere] forKey:@"commentEnvironment"];    // 环境分数
    [parameters setObject:[NSNumber numberWithInteger:self.model.restaurant_service] forKey:@"commentService"];        // 服务分数
    if (self.model.restaurant_reviewText.length>0) {
        [parameters setObject:self.model.restaurant_reviewText forKey:@"commentContent"];   // 评论内容
    }
    if (self.model.restaurant_images.count>0) {
        [parameters setObject:self.model.restaurant_images forKey:@"photoUrls"];    // 评论图片,包括大图和小图地址如：（小图地址&&大图地址）中间用&&符合连接，一定要对应出现
    }
    
    WS(weakSelf)
    [LZUserOperationPresenter saveRestaurantCommentWithParameters:parameters ResultSuccess:^{
        DLog(@"评价餐厅成功");
        weakSelf.restaurant_status = UploadReviewStauts_SuccessRequest;
        [weakSelf.table reloadData];
        [weakSelf checkUploadRequestStatus];
    } ResultFailed:^(NSString *remind) {
        DLog(@"评价餐厅失败 === %@",remind);
        weakSelf.restaurant_status = UploadReviewStauts_FaildRequest;
        [weakSelf checkUploadRequestStatus];
    }];
}

// ****************************** 视频 ******************************
// 添加视频的评论
- (void)requestUploadVideoImage {
    
    self.video_status = UploadReviewStauts_StartRequest;
    
    if (self.video_reviewPictureCell.arrImages.count>0) {
        WS(weakSelf)
        NSMutableArray *taskArray = [NSMutableArray array];
        for (int i = 0; i<self.video_reviewPictureCell.arrImages.count; i++) {
            NSURLSessionDataTask *task = [self requestUploadImage:self.video_reviewPictureCell.arrImages[i] andBusinessId:nil andBusinessType:@"6" andBusinessNo:[NSString stringWithFormat:@"%d",i] andCount:1 andSuccessBlock:^(id data) {
                [weakSelf addVideoImageUrl:data];
            } andFaildBlcok:^{
                DLog(@"视频类上传图片失败了！！！");
                weakSelf.video_status = UploadReviewStauts_FaildRequest;
                for (NSURLSessionDataTask *tempTask in taskArray) {
                    [tempTask cancel];
                }
                [taskArray removeAllObjects];
                [weakSelf.model.video_images removeAllObjects];
                [weakSelf checkUploadRequestStatus];
            }];
            
            [taskArray addObject:task];
        }
    }
    else {
        [self requestUploadVideoModel];
    }
}

// 存视频类上传的图片的url
- (void)addVideoImageUrl:(NSString*)url {
    [self.model.video_images addObject:url];
    if (self.model.video_images.count == self.video_reviewPictureCell.arrImages.count) {
        [self requestUploadVideoModel];
    }
}

// 上传视频的评价
- (void)requestUploadVideoModel {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.sellerId forKey:@"sellerId"];              // 商户id
    [parameters setObject:self.videoId forKey:@"promotionId"];            // 视频id
    [parameters setObject:[NSNumber numberWithInteger:self.model.video_rating] forKey:@"commentScore"]; // 评论分数
    
    if (self.model.video_reviewText.length>0) {
        [parameters setObject:self.model.video_reviewText forKey:@"commentContent"];   // 评论内容
    }
    if (self.model.video_images.count>0) {
        [parameters setObject:self.model.video_images forKey:@"photoUrls"];    // 评论图片,包括大图和小图地址如：（小图地址&&大图地址）中间用&&符合连接，一定要对应出现
    }
    if (self.video_noRemarkId.length>0) {
        [parameters setObject:self.video_noRemarkId forKey:@"noRemarkId"];            // 待评论优惠视频ID如果评论为待评论则必填
    }
    
    WS(weakSelf)
    [LZUserOperationPresenter saveVideoCommentWithParameters:parameters ResultSuccess:^{
        DLog(@"评价视频成功");
        weakSelf.video_status = UploadReviewStauts_SuccessRequest;
        [weakSelf.table reloadData];
        [weakSelf checkUploadRequestStatus];
        
    } ResultFailed:^(NSString *remind) {
        DLog(@"评价视频失败 === %@",remind);
        weakSelf.video_status = UploadReviewStauts_FaildRequest;
        [weakSelf checkUploadRequestStatus];
    }];
}

// ****************************** 上传图片 ******************************
// 上传图片接口
- (NSURLSessionDataTask*)requestUploadImage:(UIImage*)aImage andBusinessId:(NSString*)businessId andBusinessType:(NSString*)businessType andBusinessNo:(NSString*)businessNo andCount:(NSInteger)count andSuccessBlock:(void(^)(id data))successBlock andFaildBlcok:(void(^)())faildBlcok{
    __block NSInteger num = count;
    WS(weakSelf)
    NSURLSessionDataTask *task = [LZUploadImagePresenter uploadImage:aImage
                          andBusinessId:businessId
                        andBusinessType:businessType
                          andBusinessNo:businessNo
                             andIsThumb:YES
                                andSize:CGSizeZero
                               andBlock:^(id data, NSError *error) {
                                   if ([[data objectForKey:@"statusCode"] integerValue] == kCodeSuccesss) {
                                       DLog(@"上传图片成功");
                                       NSArray *resultArray = data[@"data"];
                                       if (resultArray.count>0) {
                                           NSDictionary *dic = resultArray[0];
                                           NSString *fileMaxPath = dic[@"filePath"];
                                           NSString *fileMinPath = dic[@"imgMinPath"];
                                           if (successBlock) {
                                               successBlock([NSString stringWithFormat:@"%@&&%@",fileMinPath,fileMaxPath]);    // （小图地址&&大图地址）中间用&&符合连接，一定要对应出现
                                           }
                                       }
                                   }
                                   else {
                                       DLog(@"上传图片 error: %@", error);
                                       num += 1;
                                       if (num == 6) {
                                           if (faildBlcok) {
                                               faildBlcok();
                                           }
                                           return ;
                                       }
                                       [weakSelf requestUploadImage:aImage andBusinessId:businessId andBusinessType:businessType andBusinessNo:businessNo andCount:num andSuccessBlock:successBlock andFaildBlcok:faildBlcok];
                                   }
                               }];
    return task;
}

// 判断两个上传接口的状态
- (void)checkUploadRequestStatus {
    
    if (self.type == WriteReviewType_Video) {
        if (self.video_status == UploadReviewStauts_SuccessRequest && self.restaurant_status == UploadReviewStauts_SuccessRequest) {
            // 如果同时上传视频评论和餐厅评论，并且都成功了
            DLog(@"视频类型_同时上传视频评论和餐厅评论，并且都成功了");
            [self uploadSuccessBackAction];
        }
        else if (self.video_status == UploadReviewStauts_FaildRequest && self.restaurant_status == UploadReviewStauts_FaildRequest) {
            // 如果同时上传视频评论和餐厅评论，并且都失败了
            DLog(@"视频类型_同时上传视频评论和餐厅评论，并且都失败了");
            [self showFaildAlert];
        }
        else if (self.video_status == UploadReviewStauts_SuccessRequest && self.restaurant_status == UploadReviewStauts_FaildRequest) {
            // 如果同时上传视频评论和餐厅评论，但是上传视频评论成功了、上传餐厅评论失败了
            DLog(@"视频类型_同时上传视频评论和餐厅评论，但是上传视频评论成功了、上传餐厅评论失败了");
            [self showFaildAlert];
        }
        else if (self.video_status == UploadReviewStauts_FaildRequest && self.restaurant_status == UploadReviewStauts_SuccessRequest) {
            // 如果同时上传视频评论和餐厅评论，但是上传视频评论失败了、上传餐厅评论成功了
            DLog(@"视频类型_同时上传视频评论和餐厅评论，但是上传视频评论失败了、上传餐厅评论成功了");
            [self showFaildAlert];
        }
        else if (self.video_status == UploadReviewStauts_SuccessRequest && self.model.restaurant_taste == 0) {
            // 只上传视频评价，并且成功了
            DLog(@"视频类型_只上传视频评价，并且成功了");
            [self uploadSuccessBackAction];
        }
        else if (self.video_status == UploadReviewStauts_FaildRequest && self.model.restaurant_taste == 0) {
            // 只上传视频评价，并且失败了
            DLog(@"视频类型_只上传视频评价，并且失败了");
            [self showFaildAlert];
        }
    }
    else if (self.type == WriteReviewType_Restaurant){
        // 上传餐厅的评价
        if (self.restaurant_status == UploadReviewStauts_SuccessRequest) {
            [self uploadSuccessBackAction];
        }
        else {
            DLog(@"失败，弹弹弹弹弹弹弹弹弹弹弹弹弹弹弹");
            [self showFaildAlert];
        }
    }
}

- (void)uploadSuccessBackAction {
    self.rightButton.userInteractionEnabled = YES;
    [self stopLoadingViewForView:self.view];
    [LZRemindView initWithImage:[UIImage imageNamed:@"提示对勾"] andContent:LZLocalizedString(@"restaurant_upload_success_remind", nil)];
    if (self.uploadReviewBlock) {
        self.uploadReviewBlock(YES);
    }
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showFaildAlert {
    self.rightButton.userInteractionEnabled = YES;
    [self stopLoadingViewForView:self.view];
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"restaurant_upload_faild_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
}

#pragma mark - ConfigUI method

// 初始化数据
-(void)configData {
    WS(weakSelf);
    self.model = [[LAWriteReviewModel alloc] init];
    self.model.isVideoReview = (self.type == WriteReviewType_Video);
    self.model.canSubmitBlock = ^(BOOL isCanSubmit) {
        if (isCanSubmit) {
            [weakSelf.rightButton setTitleColor:UIColorFromRGB(0xff7a21, 1) forState:UIControlStateNormal];
        }
        else {
            [weakSelf.rightButton setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
        }
        weakSelf.rightButton.userInteractionEnabled = isCanSubmit;
    };
    self.model.canPopBlock = ^(BOOL isCanPop) {
        if (isCanPop) {
            if (weakSelf.restaurant_reviewPictureCell.arrImages.count>0 || weakSelf.video_reviewPictureCell.arrImages.count>0) {
                weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
            }
            else {
                weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
            }
        }
        else {
            weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
        }
    };
}

// 初始化提交按钮
- (void)configNavigationBarButton {
    
    // 返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 60, 40);
    
    UIImage *image_back = [UIImage imageNamed:@"返回键_头部"];
    [backButton setImage:image_back forState:UIControlStateNormal];
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(backButton.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [backButton setLanguageRotaion];
    }
    [backButton addTarget:self action:@selector(navigationBarLeftButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self navigationItemSetting:@[backButton] type:NAVIGATIONITEMSETTING_LEFT];
    
    // 提交按钮
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightButton setTitle:LZLocalizedString(@"review_submit", nil) forState:UIControlStateNormal];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.rightButton setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    [self.rightButton sizeToFit];
    self.rightButton.frame = CGRectMake(0, 0, CGRectGetWidth(self.rightButton.bounds), 40);
    self.rightButton.userInteractionEnabled = NO;
    [self.rightButton addTarget:self action:@selector(navigationBarRightButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self navigationItemSetting:@[self.rightButton] type:NAVIGATIONITEMSETTING_RIGHT];
}

- (void)navigationBarLeftButtonClickAction:(UIButton*)sender {
    //返回action
    [self.view endEditing:YES];
    if ([self navigationShouldPopOnBackButton]) {
        self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [self showPopAlert];
    }
}

// 提交按钮点击事件
- (void)navigationBarRightButtonClickAction:(UIButton*)sender {
    if (self.type == WriteReviewType_Video) {
        // *********************** 评价视频条件下的餐厅评价判断 ***********************
        // 如果  选择了评分并且写好了评价  或者  没有选择评分并且没有写评价
        if ([self.model writeVideoReviewTypeRestaurantIsComplete]) {
            // 如果  没有选择评分并且没有写评价 并且选择图片， 则需要提示完成信息
            if (self.model.restaurant_taste == 0 && self.restaurant_reviewPictureCell.arrImages.count>0) {
                DLog(@"Please complete the restaurant review!");
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"review_completed_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
            }
            else {
                // can request
                [self requestUplodModel];
            }
        }
        else {
            DLog(@"Please complete the restaurant review!");
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"review_completed_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
            [alert show];
        }
    }
    else {
        [self requestUplodModel];
    }
}

- (BOOL)navigationShouldPopOnBackButton {
    
    if (self.model.restaurant_rating>0 || self.model.restaurant_taste>0 || self.model.restaurant_atmopsphere>0 || self.model.restaurant_service>0 || self.model.restaurant_reviewText.length>0 || self.restaurant_reviewPictureCell.arrImages.count>0 || self.video_reviewPictureCell.arrImages.count>0 || self.model.video_rating>0 || self.model.video_reviewText.length>0) {
        // 如果有编辑状态
        return NO;
    }
    return YES;
}

- (void)showPopAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"review_quit_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        if (index == 1) {
            weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    };
}


// 注册和创建cell
-(void)regisiterAndCreateCell {
    
     WS(weakSelf);
    
    // 餐厅的评分cell
    [self.table registerNib:[UINib nibWithNibName:@"LAWriteReviewScoreTableViewCell" bundle:nil] forCellReuseIdentifier:@"cellScore"];
    
    // 餐厅的评价cell
    self.restaurant_reviewTextCell = [[[NSBundle mainBundle] loadNibNamed:@"LAWriteReviewTextTableViewCell" owner:self options:nil] firstObject];
    self.restaurant_reviewTextCell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.restaurant_reviewTextCell.haveTextBlock = ^(BOOL isHave) {
        if (isHave) {
            weakSelf.model.restaurant_reviewText = [weakSelf.restaurant_reviewTextCell getReviewText];
        }
        else {
            weakSelf.model.restaurant_reviewText = @"";
        }
    };
    
    // 餐厅的图片cell
    self.restaurant_reviewPictureCell = [[[NSBundle mainBundle] loadNibNamed:@"LAWriteReviewPictureTableViewCell" owner:self options:nil] firstObject];
    self.restaurant_reviewPictureCell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.restaurant_reviewPictureCell.addNewPictureBlock = ^(){
        weakSelf.selected_reviewPictureCell = weakSelf.restaurant_reviewPictureCell;
        [weakSelf showSheetView];
    };
    
    self.restaurant_reviewPictureCell.haveDataBlock = ^(BOOL isHave) {
        if (isHave) {
            weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
        }
        else
        {
            if ([weakSelf navigationShouldPopOnBackButton]) {
                weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
            }
            else {
                weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
            }
        }
    };
    
    // *************************** 如果是视频评价 ***************************
    if (self.type == WriteReviewType_Video) {
        
        // 视频的评分cell
        self.video_RatingScoreCell = [[[NSBundle mainBundle] loadNibNamed:@"LAWriteReviewScoreTableViewCell" owner:self options:nil] firstObject];
        self.video_RatingScoreCell.model = self.model;
        self.video_RatingScoreCell.isVideoWriteReviewType = YES;
        self.video_RatingScoreCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self cellRefreshData:self.video_RatingScoreCell indexRow:0];

        // 视频的评价cell
        self.video_reviewTextCell = [[[NSBundle mainBundle] loadNibNamed:@"LAWriteReviewTextTableViewCell" owner:self options:nil] firstObject];
        self.video_reviewTextCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.video_reviewTextCell.haveTextBlock = ^(BOOL isHave) {
            if (isHave) {
                weakSelf.model.video_reviewText = [weakSelf.video_reviewTextCell getReviewText];
            }
            else {
                weakSelf.model.video_reviewText = @"";
            }
        };
        
        // 视频的图片cell
        self.video_reviewPictureCell = [[[NSBundle mainBundle] loadNibNamed:@"LAWriteReviewPictureTableViewCell" owner:self options:nil] firstObject];
        self.video_reviewPictureCell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.video_reviewPictureCell.addNewPictureBlock = ^(){
            weakSelf.selected_reviewPictureCell = weakSelf.video_reviewPictureCell;
            [weakSelf showSheetView];
        };
        
        self.video_reviewPictureCell.haveDataBlock = ^(BOOL isHave) {
            if (isHave) {
                weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
            }
            else
            {
                if ([weakSelf navigationShouldPopOnBackButton]) {
                    weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
                }
                else {
                    weakSelf.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
                }
            }
        };

    }
}

#pragma mark -TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.type == WriteReviewType_Video) {
        // *************************** 如果是视频评价 ***************************
        return 2;
    }
    // *************************** 如果是餐馆评价 ***************************
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.type == WriteReviewType_Video) {
        // *************************** 如果是视频评价 ***************************
        if (section == 0) {
            return 3;
        }
        else {
            return self.restaurantHeaderView.selected?6:0;
        }
    }
    // *************************** 如果是餐馆评价 ***************************
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.type == WriteReviewType_Video) {
        // *************************** 如果是视频评价 ***************************
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                return 51;
            }
            else if (indexPath.row == 1) {
                return [self.video_reviewTextCell cellHeight];
            }
            else {
                CGFloat cellHeight = [LAWriteReviewPictureTableViewCell cellHeight];
                return cellHeight;
            }
        }
        else {
            if (indexPath.row == 0) {
                return 51;
            }
            else if (indexPath.row >0 && indexPath.row < 4) {
                return 41;
            }
            else if (indexPath.row == 4) {
                return [self.restaurant_reviewTextCell cellHeight];
            }
            else {
                CGFloat cellHeight = [LAWriteReviewPictureTableViewCell cellHeight];
                return cellHeight;
            }
        }
    }
    
    // *************************** 如果是餐馆评价 ***************************
    if (indexPath.row == 0) {
        return 51;
    }
    else if (indexPath.row >0 && indexPath.row < 4) {
        return 41;
    }
    else if (indexPath.row == 4) {
        return [self.restaurant_reviewTextCell cellHeight];
    }
    else {
        CGFloat cellHeight = [LAWriteReviewPictureTableViewCell cellHeight];
        return cellHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.type == WriteReviewType_Video) {
        // *************************** 如果是视频评价 ***************************
        if (section == 1) {
            return CGRectGetHeight(self.restaurantHeaderView.bounds);
        }
    }
    // *************************** 如果是餐馆评价 ***************************
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    // *************************** 如果是视频评价 ***************************
    if (self.type == WriteReviewType_Video) {
        if (section == 0) {
            return 10;
        }
    }
    // *************************** 如果是餐馆评价 ***************************
    return 0.01;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.type == WriteReviewType_Video) {
        if (section == 1) {
            return self.restaurantHeaderView;
        }
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // *************************** 如果是视频评价 ***************************
    if (self.type == WriteReviewType_Video) {
        if (indexPath.section == 0) {
            UITableViewCell *cell = [self tableView:tableView videoCellForRowAtIndexPath:indexPath];
            cell.userInteractionEnabled = (self.video_status != UploadReviewStauts_SuccessRequest);
            return cell;
        }
        else {
            UITableViewCell *cell = [self tableView:tableView restaurantCellForRowAtIndexPath:indexPath];
            cell.userInteractionEnabled = (self.restaurant_status != UploadReviewStauts_SuccessRequest);
            return cell;
        }
    }
    // *************************** 如果是餐馆评价 ***************************
    else {
        UITableViewCell *cell = [self tableView:tableView restaurantCellForRowAtIndexPath:indexPath];
        cell.userInteractionEnabled = (self.restaurant_status != UploadReviewStauts_SuccessRequest);
        return cell;
    }
    
    return nil;
}

// *************************** 视频评价的cell ***************************
- (UITableViewCell *)tableView:(UITableView *)tableView videoCellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return self.video_RatingScoreCell;
    }
    else if (indexPath.row == 1) {
        return self.video_reviewTextCell;
    }
    else {
        return self.video_reviewPictureCell;
    }
}

// *************************** 餐馆评价的cell ***************************
- (UITableViewCell *)tableView:(UITableView *)tableView restaurantCellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 4) {
        LAWriteReviewScoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellScore"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.indexPath = indexPath;
        [self cellRefreshData:cell indexRow:indexPath.row];
        cell.model = self.model;
        return cell;
    }
    else if (indexPath.row == 4) {
        return self.restaurant_reviewTextCell;
    }
    else {
        
        return self.restaurant_reviewPictureCell;
        
    }
}

-(void)cellRefreshData:(LAWriteReviewScoreTableViewCell*)cell indexRow:(NSInteger)row {
    NSString *title = @"";
    switch (row) {
        case 0:
        {
            title = [NSString stringWithFormat:@"%@:",LZLocalizedString(@"rating", nil)] ;
        }
            break;
        case 1:
        {
            title = [NSString stringWithFormat:@"%@:",LZLocalizedString(@"taste", nil)];
        }
            break;
        case 2:
        {
            title = [NSString stringWithFormat:@"%@:",LZLocalizedString(@"atmosphere", nil)];
        }
            break;
        case 3:
        {
            title = [NSString stringWithFormat:@"%@:",LZLocalizedString(@"service", nil)];
        }
            break;

        default:
            break;
    }
    cell.labTitle.text = title;
    if (row == 0) {
        for (UIButton *aButton in cell.arrButtons) {
            [aButton setImage:[UIImage imageNamed:@"comment_score_unselected"] forState:UIControlStateNormal];
            [aButton setImage:[UIImage imageNamed:@"comment_score_selected"] forState:UIControlStateSelected];
        }
    }
    else {
        for (UIButton *aButton in cell.arrButtons) {
            [aButton setImage:[UIImage imageNamed:@"comment_satisfaction_unselected"] forState:UIControlStateNormal];
            [aButton setImage:[UIImage imageNamed:@"comment_satisfaction_selected"] forState:UIControlStateSelected];
        }
    }
    
}

#pragma mark - restaurantHeaderViewControl的GET方法
- (LZRestaurantHeaderViewControl*)restaurantHeaderView {
    if (_restaurantHeaderView) {
        return _restaurantHeaderView;
    }
    
    _restaurantHeaderView = [[LZRestaurantHeaderViewControl alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 52)];
    
    WS(weakSelf)
    _restaurantHeaderView.ClickBolck = ^(BOOL isSelected) {
        [weakSelf.table reloadData];
    };
    
    return _restaurantHeaderView;
}

#pragma mark - sheetView的GET方法
- (LZActionSheet*)sheetView {
    if (_sheetView) {
        return _sheetView;
    }
    
    LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:self.navigationController.view.bounds];
    _sheetView = sheet;
    [self.navigationController.view addSubview:_sheetView];
    
    WS(weakSelf)
    _sheetView.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
        if (indexPath.section == 0) {
            [weakSelf LASheetClickedButtonAtIndex:indexPath.row];
        }
    };
    
    return _sheetView;
}

- (void)showSheetView {
    [self.sheetView creatHeaderWithTitle:LZLocalizedString(@"review_uplad_num_remind", nil) andHeight:50];
    
    [self.sheetView ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"change_takephoto", nil),LZLocalizedString(@"change_choosephoto", nil)],@[LZLocalizedString(@"cancel", nil)]]];
    [self.sheetView ShowView];
}

- (void)LASheetClickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType = 0;
    
    if (buttonIndex == 0) {
        // TakePhotos
        sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    else if (buttonIndex == 1) {
        // PhotoAlbums
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
    }
    
    [self.pictureManager choosePictureWithSourceType:sourceType andPresenterVC:self];
}

#pragma mark - pictureManager的GET方法
- (LZImagePickerManager*)pictureManager {
    if (_pictureManager) {
        return _pictureManager;
    }
    LZImagePickerManager *manager = [[LZImagePickerManager alloc] init];
    manager.allowsEditing = NO;
    manager.delegate = self;
    _pictureManager = manager;
    return _pictureManager;
}

#pragma mark - LZPictureManagerDelegate
- (void)LZPictureManagerFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *aImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (aImage) {
        [self.selected_reviewPictureCell addNewPicture:aImage];
    }
}
@end
